package com.micro.ai.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.template.entity.TemplateRating;
import com.micro.ai.template.mapper.TemplateRatingMapper;
import com.micro.ai.template.service.TemplateRatingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模板评分Service实现
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateRatingServiceImpl extends ServiceImpl<TemplateRatingMapper, TemplateRating>
        implements TemplateRatingService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TemplateRating createOrUpdateRating(TemplateRating templateRating) {
        log.info("创建或更新评分, templateId: {}, userId: {}, rating: {}", 
                templateRating.getTemplateId(), templateRating.getUserId(), templateRating.getRating());

        // 检查是否已经评分
        LambdaQueryWrapper<TemplateRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateRating::getTemplateId, templateRating.getTemplateId())
                .eq(TemplateRating::getUserId, templateRating.getUserId());
        
        TemplateRating existingRating = this.getOne(wrapper);
        
        if (existingRating != null) {
            // 更新现有评分
            existingRating.setRating(templateRating.getRating());
            existingRating.setComment(templateRating.getComment());
            existingRating.setUpdatedAt(LocalDateTime.now());
            this.updateById(existingRating);
            log.info("评分更新成功, ratingId: {}", existingRating.getId());
            return existingRating;
        } else {
            // 创建新评分
            templateRating.setCreatedAt(LocalDateTime.now());
            templateRating.setUpdatedAt(LocalDateTime.now());
            this.save(templateRating);
            log.info("评分创建成功, ratingId: {}", templateRating.getId());
            return templateRating;
        }
    }

    @Override
    public IPage<TemplateRating> getRatingsByTemplateId(String templateId, Page<TemplateRating> page) {
        LambdaQueryWrapper<TemplateRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateRating::getTemplateId, templateId)
                .orderByDesc(TemplateRating::getCreatedAt);
        
        return this.page(page, wrapper);
    }

    @Override
    public TemplateRating getUserRating(String templateId, String userId) {
        LambdaQueryWrapper<TemplateRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateRating::getTemplateId, templateId)
                .eq(TemplateRating::getUserId, userId);
        
        return this.getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRating(String ratingId, String userId) {
        log.info("删除评分, ratingId: {}, userId: {}", ratingId, userId);

        TemplateRating rating = this.getById(ratingId);
        if (rating == null) {
            throw new BusinessException("评分不存在");
        }

        // 验证是否是评分的创建者
        if (!rating.getUserId().equals(userId)) {
            throw new BusinessException("无权删除此评分");
        }

        this.removeById(ratingId);
        log.info("评分删除成功, ratingId: {}", ratingId);
    }

    @Override
    public Map<String, Object> getAverageRating(String templateId) {
        LambdaQueryWrapper<TemplateRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateRating::getTemplateId, templateId);
        
        List<TemplateRating> ratings = this.list(wrapper);
        
        Map<String, Object> result = new HashMap<>();
        if (ratings.isEmpty()) {
            result.put("averageRating", 0.0);
            result.put("totalRatings", 0);
            return result;
        }

        double average = ratings.stream()
                .mapToInt(TemplateRating::getRating)
                .average()
                .orElse(0.0);

        result.put("averageRating", Math.round(average * 10.0) / 10.0);
        result.put("totalRatings", ratings.size());
        
        return result;
    }

    @Override
    public Map<Integer, Long> getRatingDistribution(String templateId) {
        LambdaQueryWrapper<TemplateRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateRating::getTemplateId, templateId);
        
        List<TemplateRating> ratings = this.list(wrapper);
        
        // 统计每个星级的数量
        Map<Integer, Long> distribution = ratings.stream()
                .collect(Collectors.groupingBy(TemplateRating::getRating, Collectors.counting()));

        // 确保所有星级都有值（1-5）
        for (int i = 1; i <= 5; i++) {
            distribution.putIfAbsent(i, 0L);
        }

        return distribution;
    }
}

